<template>
    <div class="text-view-container">
        <!-- 页面头部 -->
        <div class="header">
            <div class="header-row">
                <el-button type="primary" icon="Back" @click="goBack" class="back-btn">
                    <i class="el-icon-back"></i>返回文件列表
                </el-button>
        </div>
        <div class="header-row">
            <h2 class="header-title">文本内容管理 - {{ fileName }}</h2>
        </div>
    </div>

    <!-- 文本卡片网格 -->
    <div class="text-grid" v-loading="loading">
        <el-row :gutter="20">
            <el-col v-for="(textItem, index) in textList" :key="textItem.vector_id" :xs="24" :sm="12" :md="8" :lg="6"
                class="text-col">
                <el-card class="text-card" shadow="hover" :body-style="{ padding: '16px' }">


                    <!-- 文本信息 -->
                    <div class="text-info">
                        <div class="info-item">
                            <span class="label">文件:</span>
                            <span class="value">{{ textItem.file_name }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">创建时间:</span>
                            <span class="value">{{ formatDate(textItem.create_date) }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">向量ID:</span>
                            <span class="value vector-id">{{ textItem.vector_id }}</span>
                        </div>
                    </div>

                    <!-- 文本预览内容 -->
                    <div class="text-preview">
                        <div class="text-content">
                            {{ truncateText(textItem.text_content, 150) }}
                        </div>
                    </div>




                    <!-- 操作按钮 -->
                    <div class="text-actions">
                        <el-button type="primary" size="small" @click="showTextDetail(textItem)" class="view-btn">
                            <i class="el-icon-view"></i> 查看文字
                        </el-button>
                        <el-button type="warning" size="small" @click="openEditDialog(textItem)"
                            :disabled="editingId === textItem.vector_id" :loading="editingId === textItem.vector_id"
                            class="edit-btn">
                            <i class="el-icon-edit"></i>
                            {{ editingId === textItem.vector_id ? '编辑中...' : '编辑' }}
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteText(textItem)" class="delete-btn">
                            <i class="el-icon-delete"></i> 删除
                        </el-button>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>

    <!-- 空状态提示 -->
    <div v-if="textList.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无文本数据" />
    </div>

    <!-- 分页控件 -->
    <div v-if="totalItems > pageSize" class="pagination-container">
        <el-pagination background layout="prev, pager, next, sizes, total" :total="totalItems" :page-size="pageSize"
            :current-page="currentPage" @size-change="handleSizeChange" @current-change="handlePageChange" />
    </div>

    <!-- 文本详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="文本详情" width="80%" top="5vh" class="text-detail-dialog"
        :close-on-click-modal="true">
        <div class="dialog-content">
            <div class="text-header">
                <h3>{{ currentTextItem.file_name }}</h3>
                <span class="create-time">
                    创建时间: {{ formatDate(currentTextItem.create_date) }}
                </span>
            </div>
            <div class="text-full-content">
                <pre>{{ currentTextItem.text_content }}</pre>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="detailDialogVisible = false">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 新增：编辑文本弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="`编辑文本 - ${currentEditItem.file_name || ''}`" width="70%" top="5vh"
        class="text-edit-dialog" :close-on-click-modal="false" :before-close="handleEditDialogClose">
        <div class="edit-dialog-content">
            <div class="edit-header">
                <div class="file-info">
                    <span class="label">文件名称:</span>
                    <span class="value">{{ currentEditItem.file_name }}</span>
                </div>
                <div class="vector-info">
                    <span class="label">向量ID:</span>
                    <span class="value vector-id">{{ currentEditItem.vector_id }}</span>
                </div>
            </div>

            <div class="edit-form">
                <el-form :model="editForm" ref="editFormRef" label-width="80px">
                    <el-form-item label="文本内容" prop="text_content" :rules="[
                        { required: true, message: '文本内容不能为空', trigger: 'blur' },
                        { min: 1, max: 10000, message: '文本内容长度应在 1 到 10000 个字符之间', trigger: 'blur' }
                    ]">
                        <el-input v-model="editForm.text_content" type="textarea" :rows="15" placeholder="请输入文本内容"
                            resize="none" show-word-limit maxlength="10000" class="edit-textarea" />
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <template #footer>
            <div class="edit-dialog-footer">
                <el-button @click="handleEditCancel" :disabled="editLoading">
                    取消
                </el-button>
                <el-button type="primary" @click="handleEditConfirm" :loading="editLoading"
                    :disabled="!editForm.text_content.trim()">
                    {{ editLoading ? '提交中...' : '确认修改' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTextList, deleteSingleText, updateTextContent } from '@/api/text'

// 路由和路由实例
const route = useRoute()
const router = useRouter()

// 响应式数据
const textList = ref([])
const fileName = ref('')
const totalItems = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const loading = ref(false)

// 弹窗相关数据
const detailDialogVisible = ref(false)
const currentTextItem = ref({})

// 新增：编辑相关数据
const editDialogVisible = ref(false)
const currentEditItem = ref({})
const editForm = ref({
    text_content: ''
})
const editFormRef = ref(null)
const editLoading = ref(false)
const editingId = ref(null) // 当前正在编辑的项目ID

// 组件挂载时获取数据
onMounted(() => {
    fetchTextData()
})

// 获取文本数据
const fetchTextData = async () => {
    loading.value = true
    try {
        const params = {
            file_id: route.params.file_id,
            page: currentPage.value,
            page_size: pageSize.value
        }

        const response = await getTextList(params)

        if (response.data.statusCode === 200) {
            textList.value = response.data.data.list
            totalItems.value = response.data.data.total_items

            // 设置文件名
            if (textList.value.length > 0) {
                fileName.value = route.query.file_name || textList.value[0].file_name
            } else {
                fileName.value = route.query.file_name || '未知文件'
            }
        }
    } catch (error) {
        console.error('获取文本数据失败:', error)
        ElMessage.error('获取文本数据失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 截断文本用于预览
const truncateText = (text, maxLength) => {
    if (!text) return '暂无内容'
    if (text.length <= maxLength) return text
    return text.substring(0, maxLength) + '...'
}

// 格式化日期
const formatDate = (dateString) => {
    try {
        return new Date(dateString).toLocaleString('zh-CN')
    } catch {
        return '未知时间'
    }
}

// 显示文本详情
const showTextDetail = (textItem) => {
    currentTextItem.value = textItem
    detailDialogVisible.value = true
}



// 新增：打开编辑弹窗
const openEditDialog = (textItem) => {
    currentEditItem.value = textItem
    editForm.value.text_content = textItem.text_content || ''
    editingId.value = textItem.vector_id
    editDialogVisible.value = true

    // 下次DOM更新后自动聚焦到文本区域
    nextTick(() => {
        if (editFormRef.value) {
            editFormRef.value.clearValidate()
        }
    })
}

// 新增：处理编辑弹窗关闭
const handleEditDialogClose = (done) => {
    if (editLoading.value) {
        ElMessage.info('正在提交修改，请稍候...')
        return
    }

    if (editForm.value.text_content !== currentEditItem.value.text_content) {
        ElMessageBox.confirm('文本内容已修改，是否放弃修改？', '提示', {
            confirmButtonText: '放弃修改',
            cancelButtonText: '继续编辑',
            type: 'warning'
        }).then(() => {
            done()
            resetEditForm()
        }).catch(() => {
            // 用户选择继续编辑，不关闭弹窗
        })
    } else {
        done()
        resetEditForm()
    }
}

// 新增：取消编辑
const handleEditCancel = () => {
    if (editForm.value.text_content !== currentEditItem.value.text_content) {
        ElMessageBox.confirm('确定要放弃修改吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            editDialogVisible.value = false
            resetEditForm()
        })
    } else {
        editDialogVisible.value = false
        resetEditForm()
    }
}

// 新增：确认编辑
const handleEditConfirm = async () => {
    try {
        // 表单验证
        if (!editFormRef.value) return

        const valid = await editFormRef.value.validate()
        if (!valid) return

        editLoading.value = true

        const response = await updateTextContent(
            currentEditItem.value.vector_id,
            editForm.value.text_content
        )

        if (response.data.statusCode === 200) {
            // 更新本地数据
            const index = textList.value.findIndex(
                item => item.vector_id === currentEditItem.value.vector_id
            )
            if (index !== -1) {
                textList.value[index].text_content = editForm.value.text_content
            }

            ElMessage.success('文本内容更新成功')
            editDialogVisible.value = false
            resetEditForm()
        } else {
            ElMessage.error(`更新失败: ${response.data.message}`)
        }
    } catch (error) {
        console.error('更新文本内容失败:', error)
        if (error.response) {
            ElMessage.error(`更新失败: ${error.response.data.message || '服务器错误'}`)
        } else if (error.request) {
            ElMessage.error('网络连接失败，请检查网络设置')
        } else {
            ElMessage.error('更新操作失败，请稍后重试')
        }
    } finally {
        editLoading.value = false
    }
}

// 新增：重置编辑表单
const resetEditForm = () => {
    editingId.value = null
    currentEditItem.value = {}
    editForm.value.text_content = ''
    if (editFormRef.value) {
        editFormRef.value.clearValidate()
    }
}


// 删除文本（占位功能）
const deleteText = async (textItem) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除文本吗？此操作不可恢复。`,
            '确认删除',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        const response = await deleteSingleText(textItem.vector_id)

        if (response.data.statusCode === 200) {
            //核心代码：从当前列表中移除已删除项
            const index = textList.value.findIndex(item => item.vector_id === textItem.vector_id)
            if (index !== -1) {
                textList.value.splice(index, 1)
                totalItems.value -= 1
            }
            ElMessage.success('删除成功')

            if (textList.value.length === 0 && currentPage.value > 1) {
                currentPage.value -= 1
                await fetchTextData() // 返回前一页
            }
        }

    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除操作失败')
        }
    }
}

// 分页处理
const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    fetchTextData()
}

const handlePageChange = (page) => {
    currentPage.value = page
    fetchTextData()
}

// 返回上一页
const goBack = () => {
    router.go(-1)
}
</script>

<style scoped>
.text-view-container {
    padding: 20px;
    max-width: 1400px;
    margin: 0 auto;
}

.header {
    display: flex;
    flex-direction: column; /* 垂直排列 */
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.header-row {
    display: flex;
    width: 100%;
}

/* 第一行：按钮靠左 */
.header-row:first-child {
    justify-content: flex-start;
    margin-bottom: 10px; /* 添加行间距 */
}

/* 第二行：标题居中 */
.header-row:last-child {
    justify-content: center;
}

.back-btn {
    margin-right: 0;
}

.header-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    text-align: center;
}

.text-grid {
    margin-bottom: 24px;
}

.text-col {
    margin-bottom: 20px;
}

.text-card {
    height: 100%;
    transition: all 0.3s ease;
}

.text-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.text-preview {
    margin-bottom: 16px;
}

.text-content {
    line-height: 1.6;
    color: #606266;
    font-size: 14px;
    /* 使用行高计算 */
    line-height: 1.6;
    max-height: calc(1.6em * 3);
    /* 3行高度 */
    overflow: hidden;
    /* 添加标准属性（部分浏览器支持） */
    display: -webkit-box;
    display: -moz-box;
    display: box;
    -webkit-line-clamp: 3;
    -moz-line-clamp: 3;
    line-clamp: 3;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    box-orient: vertical;
    /* 添加省略号支持 */
    text-overflow: ellipsis;
}

.text-info {
    /* /* border-top: 1px solid #f0f0f0; */
    border-bottom: 1px solid #24232384;
    padding: 0px 0;
    margin: 0px 0;
}

.info-item {
    display: flex;
    margin-bottom: 6px;
    font-size: 12px;
}

.info-item:last-child {
    margin-bottom: 0;
}

.label {
    font-weight: 600;
    color: #909399;
    min-width: 60px;
    margin-right: 8px;
}

.value {
    color: #606266;
    flex: 1;
    word-break: break-all;
}

.vector-id {
    font-family: monospace;
    font-size: 11px;
}

.text-actions {
    display: flex;
    justify-content: space-between;
    gap: 8px;
}

.view-btn,
.edit-btn,
.delete-btn {
    flex: 1;
}

.empty-state {
    margin: 60px 0;
    text-align: center;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 24px;
}

/* 文本详情弹窗样式 */
.text-detail-dialog .el-dialog__body {
    padding: 0;
}

.dialog-content {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
}

.text-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e0e0e0;
}

.text-header h3 {
    margin: 0;
    color: #303133;
}

.create-time {
    color: #909399;
    font-size: 14px;
}

.text-full-content {
    background: #f8f9fa;
    border-radius: 4px;
    padding: 16px;
}

.text-full-content pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
    margin: 0;
    color: #333;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}


/* 新增：编辑弹窗样式 */
.text-edit-dialog .el-dialog__body {
    padding: 0;
}

.edit-dialog-content {
    padding: 20px;
}

.edit-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e0e0e0;
    background: #f8f9fa;
    padding: 12px 16px;
    border-radius: 4px;
}

.file-info,
.vector-info {
    display: flex;
    align-items: center;
}

.file-info .label,
.vector-info .label {
    min-width: 70px;
    font-weight: 600;
}

.edit-form {
    margin-top: 16px;
}

.edit-textarea {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
}

.edit-textarea :deep(.el-textarea__inner) {
    font-family: inherit;
    line-height: inherit;
}

.edit-dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .text-view-container {
        padding: 12px;
    }

    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .page-header h1 {
        margin: 12px 0 0 0;
        font-size: 20px;
    }

    .text-actions {
        flex-direction: column;
    }

    .text-col {
        margin-bottom: 16px;
    }
}

@media (max-width: 480px) {
    .text-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .create-time {
        margin-top: 8px;
    }
}
</style>